package tools;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeTools {

    public static int Remainder_days(Timestamp timestamp) throws Exception {
        String format="yyyy-MM-dd";//精确到天即可
        SimpleDateFormat simpleFormat = new SimpleDateFormat(format);
        /*天数差*/
        Date fromDate1 = simpleFormat.parse(timeStamp2Date(new Timestamp(System.currentTimeMillis()), format));
        Date toDate1 = simpleFormat.parse(timeStamp2Date(timestamp, format));
        long from1 = fromDate1.getTime();
        long to1 = toDate1.getTime();
        int days = (int) ((to1 - from1) / (1000 * 60 * 60 * 24));
        return days;
    }

    /**
     * 时间戳转换成日期格式字符串
     * @param format = "yyyy-MM-dd HH:mm:ss";
     * @return
     */
    public static String timeStamp2Date(Timestamp timestamp, String format) {
        String seconds;
        if (timestamp==null){
            seconds = String.valueOf(System.currentTimeMillis()/1000);
        }
        else {
            seconds= String.valueOf(timestamp.getTime()/1000);
        }
        if(seconds.isEmpty() || seconds.equals("null")){
            return "";
        }
        if(format == null || format.equals("")){
            format = "yyyy-MM-dd HH:mm";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds+"000")));
    }

    /**
     *     获得时间戳对应0点的时间戳
     * @param n 往前几天  今天是0天
     * @return
     */
    public static Timestamp formatTime(int n){
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DAY_OF_YEAR,-n);
        return new Timestamp (cal.getTimeInMillis());
    }
}
